package com.acmen.ump.core.jwt;


import com.acmen.ump.core.exception.JwtAuthenticationFailureException;
import com.acmen.ump.entity.sys.SysUser;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Acmen
 * @ClassName AuthenticationInterceptor.java
 * @Description TODO 短时间内的重复提交设置过滤
 * @CreateTime 2019年08月25日 23:38:25
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception{
        String token = httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method=handlerMethod.getMethod();
        //检查是否有PassJwtToken注解，有则跳过认证
        if (method.isAnnotationPresent(PassJwtToken.class)) {
            PassJwtToken passToken = method.getAnnotation(PassJwtToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        if(method.isAnnotationPresent(LoginRequired.class)) {
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            if(loginRequired.required()) {
                if(token == null) {
                    throw new JwtAuthenticationFailureException();
                }
                // 校验token
                if (JwtUtil.verifyToken(token, "email")){//该值需要从缓存中读取
                    return true;
                }
                else
                    throw new JwtAuthenticationFailureException();
            }
        }

        return true;
    }

    /**
     * 拦截response，给response添加jwt到响应头
     * 对于有 @ResponseBody注解的方法，此方法无法拦截
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {
        /**
         * 刷新token
         */
        SysUser user = new SysUser();
        user.setAccount("email");
        httpServletResponse.setHeader("Authorization", JwtUtil.generateToken(user,30));

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
